import utils from '@/utils/index';
import { Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import React, { useEffect, useState } from 'react';
import './locationAuth.scss';

const LocationAuth = ({ setCurLocation, featureName = '外卖功能' }) => {
  const [noAuth, setNoAuth] = useState(false);

  const getLocation = async () => {
    let localLocation = utils.getLocalEffectLocation();
    if (localLocation) {
      const { latitude, longitude } = localLocation;
      setCurLocation({ latitude, longitude });
    } else {
      Taro.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        timeout: 5000,
        success: (res) => {
          const { latitude, longitude } = res;
          const timeStamp = new Date().getTime();
          setCurLocation({ latitude, longitude });
          utils.setLocalStorage('location', { latitude, longitude, timeStamp });
        },
        fail: () => {
          setNoAuth(true);
        },
      }).catch(console.warn);
    }
  };

  const openSetting = () => {
    Taro.openSetting({
      success: function (res) {
        console.log(res.authSetting);
        if (res.authSetting['scope.userLocation']) {
          setNoAuth(false);
          getLocation();
        }
      },
    });
  };

  useEffect(() => {
    getLocation();
  }, []);

  return noAuth ? (
    <View className="LocationAuth">
      <View className="noAuthTip" onClick={openSetting}>
        <View className="tipLine">您已拒绝使用您的位置信息，将无法使用{featureName}；</View>

        {process.env.TARO_ENV === 'weapp' && (
          <View className="tipLine distop">
            如需继续使用该功能，请点击
            <Text className="blue">这里</Text>
            并允许
            <Text className="blue">&quot;使用我的地理位置&quot;</Text>
          </View>
        )}
        {process.env.TARO_ENV === 'h5' && (
          <View className="tipLine distop">
            如需继续使用该功能，请打开手机定位, 并允许微信访问您的位置
          </View>
        )}
      </View>
    </View>
  ) : null;
};

export default LocationAuth;
